//@author A0088498A
package logic;

import gui.IUserInterface;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import common.AttributeType;
import common.CommandType;
import common.Task;
import common.TaskStatus;

/**
 * Unblock Command Handler <br/>
 * Unblock command handler is used to process the unblock command, which is a
 * delete command for "block" task <br/>
 * Users can use Delete to delete "block" tasks as well as "normal" tasks, but
 * cannot use Unblock to delete a "normal" task <br/>
 * 
 */

public class UnblockCommandHandler extends CommandHandler{

	private final String SYNTAX_ERROR = "\nSyntax error. Press F10 for help\n";
	private final String UNBLOCK_SUCESSFUL = "\n\nTime slot is unblock successfully!\n%1$s";
	private final String UNBLOCK_ERROR = "\n\nError occured while unblocking the time slot\n%1$s";
	private final String PROMPT_MESSAGE = "\n\nWhich time slot do you want to unblock?\n";
	
	public UnblockCommandHandler(IUserInterface ui, String originalCommand, HashMap<AttributeType, String> attrMapping) {
		super(ui, originalCommand, attrMapping);
	}

	/**
	 * Needs to be explicitly called for the command to be started <br/>
	 * This method will first check for syntax first before executing the command <br/>
	 */
	public void start() {
		if (isSyntaxCorrect()) {
			execute();
		} else {
			pushToHistoryAsNonExecutableCommand();
			writeToConsole(SYNTAX_ERROR);
		}
	}
	
	/**
	 * Check for requirement for delete task: the name field is compulsory <br/>
	 * 
	 * @return true if the syntax is correct, otherwise false (the name field is
	 *         missing)
	 */
	private boolean isSyntaxCorrect() {
		if (_attrList.get(AttributeType.name) == null) {
			return false;
		}
		return true;
	}

	/**
	 * Execute the command by first searching for all Tasks that have the same taskName or including the taskName <br/>
	 * If there are more than 1 Task found, ask the Users to pick the Task then unblock <br/>
	 * Otherwise unblock the Task <br />
	 */
	private void execute(){
		// Retrieve the list of relative Tasks from storage
		String taskName = _attrList.get(AttributeType.name);
		assert (taskName != null);
		
		List<Task> relevantTasks =  searchFromStorage(true, taskName);
		
		// Remove all "normal" tasks
		Iterator<Task> iter = relevantTasks.iterator();
		while (iter.hasNext()) {
			Task task = iter.next();
			if (task.getStatus() != TaskStatus.block) {
				iter.remove();
			}
		}
		
		if (relevantTasks != null) {			
			//Search returns multiple results
			if (relevantTasks.size() > 1) {
				passResultToConsole (relevantTasks, PROMPT_MESSAGE);
				pushCommandToHistory(CommandType.delete, null);
				getStorage().setPreviousSearchResult(relevantTasks);
			
			//Exactly one result found
			} else if(relevantTasks.size() == 1) {
				Task deleteTask = relevantTasks.get(0);
				deleteFromStorage(deleteTask);
			} else if (relevantTasks.size() == 0) {
				// No result
				writeToConsole(NO_RESULT);
			}
		}
	}

	/**
	 * Unblock task from storage <br/>
	 * and record the Unblock command to the History
	 * @param unblockTask
	 */
	protected void deleteFromStorage(Task unblockTask){
		int task_id = unblockTask.getTaskId();

		boolean isDeleted = super.getStorage().deleteTask(task_id);  

		if (isDeleted) {
			String unblockSuccessful = String.format(UNBLOCK_SUCESSFUL, unblockTask.toString(true));
			writeToConsole(unblockSuccessful);

			pushCommandToHistory(CommandType.delete, unblockTask);

		} else {
			String unblockError = String.format(UNBLOCK_ERROR, unblockTask.toString(true));
			writeToConsole(unblockError);
		}	
	}

}
